package com.yydm.serviceacls.service.impl;

import com.yydm.commonutils.R;
import com.yydm.serviceacls.entity.LoginUser;
import com.yydm.serviceacls.entity.Permission;
import com.yydm.serviceacls.entity.User;
import com.yydm.serviceacls.service.LoginServer;
import com.yydm.serviceacls.utils.JwtUtil;
import com.yydm.serviceacls.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class LoginServerImpl implements LoginServer {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    @Override
    public R login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        List<Permission> permissions = loginUser.getPermissions();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login"+userId,loginUser);
        User user1 = loginUser.getUser();
        //把token响应给前端
        HashMap<String,Object> map = new HashMap<>();
        map.put("token",jwt);
        map.put("permissions", permissions);
        map.put("user",user1);
        return R.ok().data("map",map);
    }

    @Override
    public R logout() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser principal = (LoginUser) authentication.getPrincipal();
        Long id = principal.getUser().getId();
        redisCache.deleteObject("login:"+id);
        return R.ok().message("注销成功");
    }
}
